﻿using Quartz;
using Quartz.Spi;
using Common.Quartz.JobConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Common.Quartz
{
    /// <summary>
    /// Quartz启动服务
    /// </summary>
    public class QuartzStartup
    {
        private IJobFactory _iocJobFactory;
        private ISchedulerFactory _schedulerFactory;

        public QuartzStartup(IJobFactory iocJobfactory, ISchedulerFactory schedulerFactory)
        {
            _iocJobFactory = iocJobfactory;
            _schedulerFactory = schedulerFactory;
        }

        /// <summary>
        /// 开始服务
        /// </summary>
        /// <returns></returns>
        public async Task StartAsync()
        {
            //通过调度工厂获得调度器
            var scheduler = await _schedulerFactory.GetScheduler();
            //替换默认工厂
            scheduler.JobFactory = _iocJobFactory;

            //开启调度器
            await scheduler.Start();

            //加载Job
            var jobConfigTypeList = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(x => x.GetTypes().Where(i => i.BaseType == typeof(BaseJobConfig)))
                .ToList();

            //执行任务计划
            foreach (var configType in jobConfigTypeList)
            {
                var schedulerJobConfigService = Activator.CreateInstance(configType) as BaseJobConfig;
                if (schedulerJobConfigService != null)
                {
                    await schedulerJobConfigService.ScheduleJob(scheduler);
                }
            }
        }
    }
}
